package com.atguigu.tingshu.payment.service.impl;

import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private KafkaService kafkaService;

    @Override
    public void updatePaymentStatus(Transaction transaction) {
        //  根据orderNo 查询paymentInfo 对象.
        PaymentInfo paymentInfo = this.getOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, transaction.getOutTradeNo()));
        if (null == paymentInfo){
            return;
        }
        //  payment_info.payment_status ; out_trade_no
        //  交易编号（微信或支付）
        paymentInfo.setOutTradeNo(transaction.getTransactionId());
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
        //  回调时间，回调内容
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(transaction.toString());
        this.updateById(paymentInfo);

        //  异步发送一个消息; 看业务属于那种? 订单or充值
        String topics = paymentInfo.getPaymentType().equals(SystemConstant.PAYMENT_TYPE_ORDER)? KafkaConstant.QUEUE_ORDER_PAY_SUCCESS:KafkaConstant.QUEUE_RECHARGE_PAY_SUCCESS;
        //  发送消息
        kafkaService.sendMessage(topics,transaction.getOutTradeNo());
    }

    @Override
    public void savePaymentInfo(String orderNo, String paymentType, Long userId, BigDecimal totalAmount) {
        //  创建交易记录对象
        PaymentInfo paymentInfo = new PaymentInfo();
        //  赋值:
        paymentInfo.setUserId(userId);
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        paymentInfo.setAmount(totalAmount);
        paymentInfo.setContent(paymentType.equals(SystemConstant.PAYMENT_TYPE_ORDER)?"支付订单":"充值");
        //  0901-订单 1401-交易记录 都是未支付
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
        //  保存交易记录。
        this.save(paymentInfo);
    }
}
